package com.dudu.service.impl;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.mortbay.log.Log;
import org.springframework.beans.BeanUtils;

import com.dudu.bean.AppExtendBean;
import com.dudu.dao.AppExtendDao;
import com.dudu.model.AppExtend;
import com.dudu.service.IAppExtendService;
import com.dudu.service.ICheckValidityService;
import com.dudu.service.IOperationPlatformService;
import com.dudu.utils.EnumUtility;

import core.CoreDao;
import core.CoreDaoInvoke;
import core.util.CommUtils;

/**
 * App扩展信息实现类
 * 
 * @author 危东
 * @date 2016-4-19
 */
public class AppExtendServiceImpl implements IAppExtendService {
	// 日志输出
	private static final Logger log = Logger.getLogger(AppExtendServiceImpl.class.getSimpleName());
	// 用于App扩展信息数据库操作
	private AppExtendDao appExtendDao = new AppExtendDao();
	// 用于数据库连接
	private CoreDao coreDao = CoreDaoInvoke.getInstance();
	// 运营平台相关操作
	private IOperationPlatformService operationPlatformService = new OperationPlatformServiceImpl();

	/**
	 * 新增扩展信息
	 * 
	 * @param bean
	 * @return
	 */
	public int insertAppExtend(AppExtendBean bean) {
		return appExtendDao.insertAppExtend(coreDao, conversion(bean));
	}

	/**
	 * 更新扩展信息
	 * 
	 * @param bean
	 * @return
	 */
	public int updateAppExtend(AppExtendBean bean) {
		return appExtendDao.updateAppExtend(coreDao, conversion(bean));
	}

	/**
	 * 根据app标识查询app扩展信息
	 * 
	 * @param appIdentify
	 * @return
	 */
	@Override
	public AppExtendBean queryAppExtendByIdentify(String appIdentify) {
		log.info("IAppExtendServiceImpl.queryAppExtendByIdentify");
		// 用于返回最终结果
		AppExtendBean appExtendBean = new AppExtendBean();
		// 判断传入的appIdentify是否为空
		if (StringUtils.isNotBlank(appIdentify)) {
			// 数据库查询app扩展信息
			AppExtend appExtend = appExtendDao.queryAppExtendByIdentify(coreDao, appIdentify);
			// 判断查询的值是否为空
			if (appExtend == null) {
				// 如果查询为空，则查询结果返回为null
				appExtendBean = null;
			} else {
				appExtendBean = conversion(appExtend);
			}
		} else {
			// 如果传入的值为空，则返回null
			appExtendBean = null;
		}
		return appExtendBean;
	}

	/**
	 * 查询App 扩展信息,先调用运营平台接口查询10条,然后根据appkey查询数据库当中的扩展信息
	 * 
	 * @param page_no
	 * @param pageSize
	 * @param isvName
	 * @param app_name
	 *            3
	 * @return JSONObject(totalItemNum,items)
	 */
	public JSONObject queryAll(Integer page_no, Integer pageSize,String isvName, String app_name, String app_key) {
		JSONObject object = new JSONObject();
		// 调用接口查询应用信息
		JSONObject response = this.queryAppItems(isvName, app_name, app_key,page_no, pageSize);
		if (EnumUtility.isBlank(response) || !response.containsKey("data")) {
			object.put("totalItemNum", 0);
			object.put("items", null);
			return object;
		}
		JSONArray items = response.getJSONArray("data");
		if (null != items) {
			for (int i = 0; i < items.size(); i++) {
				JSONObject obj = items.getJSONObject(i);
				String appIdentify = obj.getString("app_key");
				// 根据应用标识查询应用扩展信息（数据库）
				AppExtend appExtend = appExtendDao.queryAppExtendByIdentify(coreDao, appIdentify);
				if (null == appExtend) {// 数据库没有，需要页面进行配置
					obj.put("isHasExtend", false);// perphery_code
					// obj.put("periphery_code", "");//periphery_code
				} else {
					obj.put("isHasExtend", true);// --periphery_code
					// obj.put("periphery_code", appExtend.getPeriphery_code());
				}

			}
			// 总条数，用于分页
			object.put("totalItemNum",Integer.parseInt(response.getString("totalNums")));
			object.put("items", items);
		} else {
			object.put("totalItemNum", 0);
			object.put("items", null);
		}
		return object;
	}

	/**
	 * 查询app 分页基础接口
	 * 
	 * @param isvName
	 * @param app_name
	 * @param page_no  页码
	 * @param page_size每页显示数据数量
	 * @return
	 */
	public JSONObject queryAppItems(String isvName, String app_name,String app_key, Integer page_no, Integer page_size) {
		return operationPlatformService.queryAppItems(isvName, app_name,app_key, page_no, page_size);
	}

	/**
	 * 查询条数（分页用）
	 * 
	 * @param paramSql
	 * @return
	 */
	public Integer getTotalAcount(String paramSql) {
		return appExtendDao.getTotalAcount(coreDao, paramSql);
	}

	/**
	 * 查询数据（分页）
	 * 
	 * @param paramSql
	 * @param pageSql
	 * @return
	 */
	public List<JSONObject> queryAll(String paramSql, String pageSql) {
		List<JSONObject> list = appExtendDao.queryAll(coreDao, paramSql,pageSql);
		return list;
	}

	/**
	 * 转化
	 * 
	 * @param menu
	 * @return
	 */
	private AppExtendBean conversion(AppExtend bean) {
		AppExtendBean appExtendBean = new AppExtendBean();
		BeanUtils.copyProperties(bean, appExtendBean);// 源,目的
		// PropertyUtils.copyProperties(dest, orig);//目的,源
		return appExtendBean;
	}

	/**
	 * 转化
	 * 
	 * @param menuBean
	 * @return
	 */
	private AppExtend conversion(AppExtendBean bean) {
		AppExtend appExtend = new AppExtend();
		BeanUtils.copyProperties(bean, appExtend);// 源,目的
		// PropertyUtils.copyProperties(dest, orig);//目的,源
		return appExtend;
	}

	public static void main(String[] args) {
		AppExtendServiceImpl s = new AppExtendServiceImpl();
		// String ss= "北京用友审计软件有限公司";queryAppItems
		// s.queryCustAppList("17001200111");
		// s.queryAppItems(null, null, 1, 10);
	}

	@Override
	public AppExtendBean qryVersionFour(JSONObject object, String appkey,String timestamp, String sign) {
		Log.info("load OpenOperateByAppKey.qryVersionFour 根据AppKey在v4版本查询相关信息");
		// 用于接收查询结果
		AppExtendBean result = new AppExtendBean();
		if (!StringUtils.isBlank(appkey) && appkey != null) {
			result = queryAppExtendByIdentify(appkey);
			if (result != null) {
				// if(checkValidityService.toolsCheckSign(appkey,result.getKey_private(),timestamp,sign)){
				setData(result, object);
				return result;
				// }
				// else{
				// object.put("result", "-1");
				// object.put("describe", "参数sign或时间错误");
				// object.put("code", "0001");
				// }
			} else {
				object.put("result", "-1");
				object.put("describe", "未找到相应应用信息！");
				object.put("code", "0002");
			}
		}

		else {
			object.put("result", "-1");
			object.put("describe", "请使用正确的应用标识");
			object.put("code", "0003");
		}
		return new AppExtendBean();
	}

	private void setData(AppExtendBean result, JSONObject object) {

		object.put("result", "0");
		object.put("appkey", result.getApp_key());
		object.put("publicKey", result.getKey_public());
		object.put("privateKey", result.getKey_private());
		object.put("urlcallstatus", result.getUrl_callstatus());
		object.put("urlticket", result.getUrl_ticket());
		object.put("urlivrdigit", result.getUrl_ivrdigit());
		object.put("urlrecord", result.getUrl_record());
	}

	@Override
	public boolean checkSign(JSONObject object, String appkey,String timestamp, String sign, AppExtendBean result) {
		ICheckValidityService checkValidityService = new CheckValidityServiceImpl();
		if (checkValidityService.toolsCheckSign(appkey,result.getKey_public(), timestamp, sign)) {
			setData(result, object);
			return true;
		} else {
			object.clear();
			object.put("result", "-1");
			object.put("describe", "参数sign或时间错误");
			object.put("code", "0001");
			return false;
		}
	}

	@Override
	public JSONObject qryVersionThree(String url, String appkey,String timestamp, String sign) {
		String method =url+"AppOper/qryInfoByAppKey.do";
		//String method = "http://localhost:9090/AppOper/qryInfoByAppKey.do";
		HashMap<String, String> m = new HashMap<String, String>();

		m.put("appkey", appkey);
		m.put("timestamp", timestamp);
		m.put("sign", sign);
		String data = "";
		JSONObject object = new JSONObject();
		try {
			data = CommUtils.getHttpClientResult(method, m);
			object = JSONObject.fromObject(data);
		} catch (IOException e) {

			e.printStackTrace();
		}
		return object;
	}

	@Override
	public JSONObject updVersionThree(JSONObject object, String url,String appkey, String timestamp, String sign) {
		 String method =url+"/AppOper/updByAppKey.do";
		//String method = "http://localhost:9090/AppOper/updByAppKey.do";
		HashMap<String, String> m = new HashMap<String, String>();

		m.put("appkey", appkey);
		m.put("timestamp", timestamp);
		m.put("sign", sign);
		m.put("privateKey", object.getString("privateKey"));
		m.put("publicKey", object.getString("publicKey"));
		m.put("urlcallstatus", object.getString("urlcallstatus"));
		m.put("urlticket", object.getString("urlticket"));
		m.put("urlivrdigit", object.getString("urlivrdigit"));
		m.put("urlrecord", "");
		m.put("linker_phone", object.getString("linker_phone"));
		String data = "";
		JSONObject objectre = new JSONObject();
		try {
			data = CommUtils.getHttpClientResult(method, m);
			objectre = JSONObject.fromObject(data);
		} catch (IOException e) {

			e.printStackTrace();
		}
		return objectre;
	}

}
